package com.xq.jltx.frescosimple.utils;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.facebook.binaryresource.BinaryResource;
import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.CacheKey;
import com.facebook.common.media.MediaUtils;
import com.facebook.common.util.UriUtil;
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.imagepipeline.request.ImageRequest;

import java.io.File;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2016年02月04日.
 */

public class FrescoUtils {

    public static final String HTTP_SCHEME = "http://";
    public static final String HTTPS_SCHEME = "https://";
    public static final String LOCAL_FILE_SCHEME = "file://";
    public static final String LOCAL_CONTENT_SCHEME = "content://";
    public static final String LOCAL_ASSET_SCHEME = "asset://";
    public static final String LOCAL_RESOURCE_SCHEME = "res://";
    public static final String DATA_SCHEME = "data://";

    public static final int OTHER_SCHEME_INT = -1;
    public static final int NET_SCHEME_INT = 0;
    public static final int LOCAL_FILE_SCHEME_INT = 1;
    public static final int LOCAL_VIDEO_FILE_SCHEME_INT = 2;
    public static final int LOCAL_CONTENT_SCHEME_INT = 3;
    public static final int LOCAL_ASSET_SCHEME_INT = 4;
    public static final int LOCAL_RESOURCE_SCHEME_INT = 5;
    public static final int DATA_SCHEME_INT = 6;

    /**
     * 判断是否缓存了http或者https的下载图片
     * @param loadUri
     * @return
     */
    public static boolean isImageDownloaded(Uri loadUri,Context context) {
        if (loadUri == null && DefaultCacheKeyFactory.getInstance() == null || ImagePipelineFactory.getInstance() == null) {
            return false;
        }
        CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(loadUri),context);
        return ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey) || ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().hasKey(cacheKey);
    }


    /**
     *判断是否缓存了图片,包括网络下载下来的图片和本地，Asset，以及Res图片
     * @param loadUri
     * @return
     */
    public static boolean isInImagePipeline(Uri loadUri,Context context){
        if (loadUri == null && DefaultCacheKeyFactory.getInstance() == null || ImagePipelineFactory.getInstance() == null && ImagePipelineFactory.getInstance().getImagePipeline() != null) {
            return false;
        }
        return ImagePipelineFactory.getInstance().getImagePipeline().isInBitmapMemoryCache(ImageRequest.fromUri(loadUri)) || isImageDownloaded(loadUri,context);
    }

    /**
     * 获取缓存图片的原始图片路径
     * @param loadUri
     * @return
     */
    public static File getCachedImageOnDisk(Uri loadUri,Context context) {
        File localFile = null;
        if (loadUri != null &&  DefaultCacheKeyFactory.getInstance() != null) {
            CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(loadUri),context);
            ImagePipelineFactory imagePipelineFactory = ImagePipelineFactory.getInstance();
            if(imagePipelineFactory != null){
                if (imagePipelineFactory.getMainDiskStorageCache().hasKey(cacheKey)) {
                    BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
                    localFile = ((FileBinaryResource) resource).getFile();
                } else if (imagePipelineFactory.getSmallImageDiskStorageCache().hasKey(cacheKey)) {
                    BinaryResource resource = ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().getResource(cacheKey);
                    localFile = ((FileBinaryResource) resource).getFile();
                }
            }

        }
        return localFile;
    }


    /**
     *普通路径转成uri路径
     * @param type
     * @param uriPath
     * @return
     */
    public static String getUriPathFromPath(Context context,int type, String uriPath){
        if(uriPath == null){
            return uriPath;
        }
        String packageName = "";
        if(context != null){
            packageName = context.getPackageName();
        }
        String scheme = "";
        switch (type){
            case LOCAL_FILE_SCHEME_INT:
            case LOCAL_VIDEO_FILE_SCHEME_INT:
            case DATA_SCHEME_INT:
                scheme = LOCAL_FILE_SCHEME + packageName + "/";
                break;
            case LOCAL_CONTENT_SCHEME_INT:
                scheme = LOCAL_CONTENT_SCHEME + packageName + "/";
                break;
            case LOCAL_ASSET_SCHEME_INT:
                scheme = LOCAL_ASSET_SCHEME + packageName + "/";
                break;
            default:
                break;
        }
        return scheme + uriPath;
    }

    /**
     * resoure资源转成uri的路径
     * @param context
     * @param uriRes
     * @return
     */
    public static String getUriPathFromRes(Context context,int uriRes){
        String packageName = "";
        if(context != null){
            packageName = context.getPackageName();
        }
        return LOCAL_RESOURCE_SCHEME + packageName + "/" + uriRes;
    }
    /**
     * 判断要加载的url
     * @param loadUri
     * @return
     */
    public static int getTypeImageSequence(Uri loadUri) {
        if(loadUri == null){
            return OTHER_SCHEME_INT;
        }
        if(UriUtil.isNetworkUri(loadUri)) {   //判断是否是http或者https的uri
            return NET_SCHEME_INT;
        } else if(UriUtil.isLocalFileUri(loadUri)) {  //判断是否是本地sd卡文件
            //判断该本地文件是否是视频
            if(MediaUtils.isVideo(MediaUtils.extractMime(loadUri.getPath()))){
                return LOCAL_VIDEO_FILE_SCHEME_INT;
            }else{
                return LOCAL_FILE_SCHEME_INT;
            }
        } else if(UriUtil.isLocalContentUri(loadUri)) {   //判断是否是本地Content provider文件
            return LOCAL_CONTENT_SCHEME_INT;
        } else if(UriUtil.isLocalAssetUri(loadUri)) {   //判断是否是Asset文件
            return LOCAL_ASSET_SCHEME_INT;
        } else if(UriUtil.isLocalResourceUri(loadUri)) {   //判断是否是本地resource文件
            return LOCAL_RESOURCE_SCHEME_INT;
        } else if(UriUtil.isDataUri(loadUri)) {    //判断是否是data数据文件
            return DATA_SCHEME_INT;
        } else {
            String uriString = loadUri.toString();
            if(uriString.length() > 30) {
                uriString = uriString.substring(0, 30) + "...";
            }
            throw new RuntimeException("Unsupported uri scheme! Uri is: " + uriString);
        }
    }

    /**
     * 解析resource资源的uri
     * @param loadUri
     * @return
     */
    public static int getResourceId(Uri loadUri) {
        int resId = 0;
        if(!TextUtils.isEmpty(loadUri.getPath())){
            try {
                if(loadUri.getPath().startsWith("/")){
                    resId = Integer.parseInt(loadUri.getPath().substring(1));
                }else {
                    resId = Integer.parseInt(loadUri.getPath());
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return resId;
    }

    /**
     * 解析本地图片Asset,data,sd的uri里面包含的本地路径
     * @param loadUri
     * @return
     */
    public static String  getLocalImageFile(Uri loadUri){
        String resultStr = "";
        if(loadUri != null) {
            if (!TextUtils.isEmpty(loadUri.getPath())){
                if(loadUri.getPath().startsWith("/")){
                    resultStr = loadUri.getPath().substring(1);
                }else{
                    resultStr = loadUri.getPath();
                }
            }
        }
        return resultStr;
    }

    /**
     * 获取uri的Scheme
     * @param loadUri
     * @return
     */
    public static String getSchemeOrNull(Uri loadUri) {
        return loadUri == null?null:loadUri.getScheme();
    }
}
